package com.ruoyi.tcsp.service.impl;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.tcsp.domain.bean.req.ScientificInfoReq;
import com.ruoyi.tcsp.domain.bean.resp.FileResp;
import com.ruoyi.tcsp.domain.bean.resp.ScientificInfoResp;
import com.ruoyi.tcsp.domain.mongo.ScientificInfo;
import com.ruoyi.tcsp.domain.mysql.ScientificBaseInfo;
import com.ruoyi.tcsp.mapper.ScientificBaseInfoMapper;
import com.ruoyi.tcsp.repository.ScientificInfoRepository;
import com.ruoyi.tcsp.service.ScientificInfoService;
import com.ruoyi.tcsp.utils.ConvertUtils;
import com.ruoyi.tcsp.utils.MinioUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ScientificInfoServiceImpl implements ScientificInfoService {

    public static final Logger LOG = LoggerFactory.getLogger(ScientificInfoServiceImpl.class);

    @Autowired
    private ScientificBaseInfoMapper scientificBaseInfoMapper;
    @Autowired
    private ScientificInfoRepository scientificInfoRepository;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MinioUtils minioUtils;

    /**
     * 查询科技成果
     *
     * @param scientificId 科技成果主键
     * @return 科技成果
     */
    @Override
    public ScientificInfoResp selectScientificBaseInfoByScientificId(Long scientificId)
    {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        ScientificBaseInfo baseInfo = scientificBaseInfoMapper.selectScientificBaseInfoByScientificId(scientificId);
        ScientificInfo otherInfo = scientificInfoRepository.findById(baseInfo.getPatentNo()).get();
        ScientificInfoResp resp = new ScientificInfoResp();
        resp.setScientificId(baseInfo.getScientificId());
        resp.setScientificName(baseInfo.getScientificName());
        resp.setPatentNo(baseInfo.getPatentNo());
        resp.setApplicantName(baseInfo.getApplicantName());
        resp.setPublicNumber(baseInfo.getPublicNumber());
        resp.setPublicDate(baseInfo.getPublicDate());
        resp.setAgency(baseInfo.getAgency());
        resp.setIpcType(baseInfo.getIpcType());
        resp.setInventorName(baseInfo.getInventorName());
        resp.setAgentName(baseInfo.getAgentName());
        if (baseInfo.getPublicDate() != null && !baseInfo.getPublicDate().toString().isEmpty()) {
            String publicDate = df.format(baseInfo.getPublicDate());
            resp.setApplicationDate(publicDate);
        }
        if (baseInfo.getApplicationDate() != null && !baseInfo.getApplicationDate().toString().isEmpty()) {
            String applicationDate = df.format(baseInfo.getApplicationDate());
            resp.setApplicationDate(applicationDate);
        }
        resp.setEvaluateLeval(baseInfo.getEvaluateLeval());
        resp.setStatus(baseInfo.getStatus());
        resp.setSummaryInfo(otherInfo.getSummaryInfo());
        ScientificInfo byId = mongoTemplate.findById(baseInfo.getPatentNo(), ScientificInfo.class);
        Map<String, List<String>> map = byId.getSummaryPicture();
        List<FileResp> fileUrls = new ArrayList<>();
        if (map != null && map.size() > 0) {
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                List<String> value = entry.getValue();
                for (int i = 0; i < value.size(); i++) {
                    String fileUrl = minioUtils.getFileUrl(value.get(i));
                    fileUrls.add(new FileResp(value.get(i),fileUrl));
                }
            }
        }
        String pdfUrl = byId.getPdfUrl();
        if (pdfUrl !=null && !pdfUrl.isEmpty()) {
            Map<String, String> pdfRes = new HashMap<>();
            String fileUrl = minioUtils.getFileUrl(pdfUrl);
            pdfRes.put(pdfUrl, fileUrl);
            resp.setPdfUrl(new FileResp(pdfUrl, fileUrl));
        }
        resp.setSummaryPicture(fileUrls);
        resp.setClaim(otherInfo.getClaim());
        resp.setSpecification(otherInfo.getSpecification());
        return resp;
    }

    /**
     * 查询科技成果列表
     *
     * @param ScientificBaseInfo 科技成果
     * @return 科技成果
     */
    @Override
    public List<ScientificBaseInfo> selectScientificBaseInfoList(ScientificBaseInfo ScientificBaseInfo)
    {

        List<ScientificBaseInfo> scientificBaseInfos = scientificBaseInfoMapper.selectScientificBaseInfoList(ScientificBaseInfo);
        for (int i = 0 ; i < scientificBaseInfos.size(); i++) {
            Map<String, List<String>> map = mongoTemplate.findById(scientificBaseInfos.get(i)
                            .getPatentNo(), ScientificInfo.class).getSummaryPicture();

            if (map != null && map.size() > 0) {
                List<String> list = map.get(scientificBaseInfos.get(i).getPatentNo());
                if (list != null && list.size() > 0) {
                    String fileUrl = minioUtils.getFileUrl(list.get(0));
                    scientificBaseInfos.get(i).setShowPic(fileUrl);
                }
            }
        }
        return scientificBaseInfos;
    }

    /**
     * 新增科技成果
     * @param req
     * @param loginUser
     * @return 结果
     */
    @Override
    @Transactional
    public int insertScientificBaseInfo(ScientificInfoReq req, LoginUser loginUser)
    {
        //具体插入科技成果逻辑     数据分别存入Mysql和MongoDB两个数据库当中
        ScientificBaseInfo baseInfo = ConvertUtils.convert(req);
        //设置代理机构
        SysDept sysDept = iSysDeptService.selectDeptById(loginUser.getDeptId());
        baseInfo.setAgency(sysDept.getDeptName());
        //插入mongo表 ，使用专利号  作为 mongo主键  id
        Map<String,List<String>> pictureMap = new HashMap<>();
        String[] summaryPicture = req.getSummaryPicture();
        List<String> list = new ArrayList<>();
        for (int i = 0 ; i < summaryPicture.length ; i++) {
            list.add(summaryPicture[i]);
        }
        pictureMap.put(baseInfo.getPatentNo(), list);
        ScientificInfo scientificInfo = new ScientificInfo(baseInfo.getPatentNo(),req.getSummaryInfo(),
                pictureMap,req.getPdfFile(),req.getClaim(),req.getSpecification());
        scientificInfoRepository.save(scientificInfo);
        //插入mysql中
        return scientificBaseInfoMapper.insertScientificBaseInfo(baseInfo);
    }

    /**
     * 修改科技成果
     * @return 结果
     */
    @Override
    @Transactional
    public int updateScientificBaseInfo(ScientificInfoReq req, LoginUser loginUser)
    {
        //具体插入科技成果逻辑     数据分别存入Mysql和MongoDB两个数据库当
        ScientificBaseInfo baseInfo = new ScientificBaseInfo();
        baseInfo.setScientificId(req.getScientificId());
        baseInfo.setScientificName(req.getScientificName());
        baseInfo.setApplicantName(req.getApplicantName());
        baseInfo.setInventorName(req.getInventorName());
        baseInfo.setAgentName(req.getAgentName());
        baseInfo.setIpcType(req.getIpcType());
        //设置代理机构
        //插入mongo表 ，使用专利号  作为 mongo主键  id
        Criteria criteria = new Criteria("id").is(req.getPatentNo());
        Query query = new Query().addCriteria(criteria);
        Update update = new Update();
        update.set("summaryInfo", req.getSummaryInfo());
        //Map<String, List<String>>
        Map<String, List<String>> map = new HashMap<>();
        map.put(req.getPatentNo(), Arrays.asList(req.getSummaryPicture()));
        if (req.getSummaryPicture() != null && req.getSummaryPicture().length > 0) {
            update.set("summary_picture", map);
        }
        if (req.getPdfFile() != null && !req.getPdfFile().isEmpty()) {
            //String
            update.set("pdf_url", req.getPdfFile());
        }
        update.set("claim", req.getClaim());
        update.set("specification", req.getSpecification());
        mongoTemplate.updateFirst(query, update, ScientificInfo.class);
        //插入mysql中
        return scientificBaseInfoMapper.updateScientificBaseInfo(baseInfo);
    }

    /**
     * 批量删除科技成果
     *
     * @param scientificIds 需要删除的科技成果主键
     * @return 结果
     */
    @Override
    public int deleteScientificBaseInfoByScientificIds(Long[] scientificIds)
    {
        return scientificBaseInfoMapper.deleteScientificBaseInfoByScientificIds(scientificIds);
    }

    /**
     * 删除科技成果信息
     *
     * @param scientificId 科技成果主键
     * @return 结果
     */
    @Override
    public int deleteScientificBaseInfoByScientificId(Long scientificId)
    {
        return scientificBaseInfoMapper.deleteScientificBaseInfoByScientificId(scientificId);
    }
}
